package com.homestead.xxljob;

import com.alibaba.fastjson.JSON;
import com.homestead.feign.XxlJobFeignService;
import com.xxl.job.core.biz.model.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

@Component
@Slf4j
public class XxlJobUtil {
    @Resource
    private XxlJobFeignService xxlJobFeignService;

    @Value("${xxl.job.groupId}")
    private String xxlJobGroupId;

    /**
     * 增加消息定时发送job任务
     * @param jobDesc job描述
     * @param jobhandlerName job的名称
     * @param sendTime job执行时间
     * @param jobCode 唯一的job代码
     * @param extParams job请求参数
     */
    public void addDynamicJob(LocalDateTime sendTime, String jobDesc, String jobhandlerName, String jobCode, Map<String, Object> extParams) {
        XxlJobInfo xxlJobInfo = XxlJobInfo.buildJob(sendTime);
        xxlJobInfo.setJobGroup(Integer.parseInt(xxlJobGroupId));
        xxlJobInfo.setJobDesc(jobDesc);
        xxlJobInfo.setExecutorHandler(jobhandlerName);
        xxlJobInfo.setTriggerStatus(1);
        xxlJobInfo.setExecutorParam(JSON.toJSONString(extParams));
        xxlJobInfo.setAuthor("ljy");
        //xxlJobInfo.setJobCode(jobCode);

        ReturnT<String> returnT = xxlJobFeignService.addJob(xxlJobInfo);
        if (returnT.getCode() != 200) {
            log.error("定时任务创建失败，code={}， msg={}", returnT.getCode(), returnT.getMsg());
            throw new RuntimeException("定时任务创建失败");
        }
    }

    public void removeDynamicJob(String jobCode) {
        ReturnT<String> returnT = xxlJobFeignService.removeJob(Integer.parseInt(jobCode));
        if (returnT.getCode() != 200) {
            log.error("定时任务删除失败，code={}， msg={}", returnT.getCode(), returnT.getMsg());
            throw new RuntimeException("定时任务删除失败");
        }
    }
}
